package com.ksd.web.controller.system;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import com.ksd.common.weather.CityRegionDataFromAPI;
import com.ksd.common.annotation.Log;
import com.ksd.common.config.PlayControlConfig;
import com.ksd.common.core.controller.BaseController;
import com.ksd.common.core.domain.AjaxResult;
import com.ksd.common.core.page.TableDataInfo;
import com.ksd.common.enums.BusinessType;
import com.ksd.common.utils.DateUtils;
import com.ksd.common.utils.StringUtils;
import com.ksd.common.utils.file.FileUploadUtils;
import com.ksd.quartz.util.TaskConstans;
import com.ksd.system.domain.SysBoard;
import com.ksd.system.service.ISysBoardService;
import com.ksd.system.service.impl.AsynchWeatherService;
import com.ksd.system.service.impl.SysBoardServiceImpl;
import com.ksd.web.controller.domain.City;
import com.ksd.web.controller.domain.HotelFile;
import com.ksd.web.controller.domain.Region;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ksd.system.domain.SysFirst;
import com.ksd.system.service.ISysFirstService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 终端首页配置Controller
 * 
 * @author y.wu
 * @date 2025-04-01
 */
@RestController
@RequestMapping("/system/sysFirst")
public class SysFirstController extends BaseController
{
    @Autowired
    private ISysFirstService sysFirstService;
    @Autowired
    private ISysBoardService sysBoardService;
    @Autowired
    private AsynchWeatherService asynchWeatherService;

    /**
     * 查询终端首页配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:sysFirst:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysFirst sysFirst)
    {
        startPage();
        List<SysFirst> list = sysFirstService.selectSysFirstList(sysFirst);
        List<SysFirst> newList = new ArrayList<>();
        SysBoard sysBoard = sysBoardService.selectSysBoardById(SysBoard.serviceFileId);
        String serviceUrl = sysBoard.getUrl();
        for (SysFirst first : list) {
            String keyId = first.getKeyId();
            if (keyId.equals(TaskConstans.first_key_weather_index)) {
                continue;
            }
            if (keyId.equals(TaskConstans.first_key_apk_describe_index)){
                first.setValue1(first.getDescription());
            }
            if (keyId.equals(TaskConstans.first_key_back_style)){
                String value2 = first.getValue2();
                if (value2.equals("1")){
                    first.setRemark("首页背景设置图片");
                    first.setImageUrl(serviceUrl+first.getValue1());
                    first.setValue1(serviceUrl+first.getValue1());
                }else if (value2.equals("0")){
                    first.setRemark("首页背景设置颜色");
                    first.setValue1(first.getValue3());
                }
            }
            if (keyId.startsWith(TaskConstans.first_key_picture_index)){
                first.setValue1(serviceUrl+first.getValue1());
                first.setValue2(serviceUrl+first.getValue2());
            }
            newList.add(first);
        }
        return getDataTable(newList);
    }

    @GetMapping("/getCities")
    public AjaxResult getCities() {
        List<City> cities = new ArrayList<>();
        String country = "中华人民共和国";
        List<String> regionsByCity = CityRegionDataFromAPI.getRegionsByCity(country);
        Long index = 0l;
        for (String s : regionsByCity) {
            index++;
            City city = new City();
            city.setId(index);
            city.setName(s);
            cities.add(city);
        }
        return success(cities);
    }

    @PutMapping("/updatePicOrVideo")
    public AjaxResult updatePicOrVideo(@RequestBody HotelFile hotelFile) throws Exception
    {
        String imageFile = hotelFile.getImageUrl();
        String videoFile = hotelFile.getVideoUrl();
        String id = hotelFile.getId();
        logger.info(imageFile);
        logger.info(videoFile);
        logger.info(id);
        // 上传并返回新文件名称
//        SysBoard sysBoard = sysBoardService.selectSysBoardById(SysBoard.serviceFileId);
//        String serviceIpUrl = sysBoard.getUrl();
        SysFirst sysFirst = sysFirstService.selectSysFirstById(Long.valueOf(id));
//        if (imageFile.startsWith(sysBoard.getUrl())){
            sysFirst.setValue1(imageFile);
//        }else{
//            sysFirst.setValue1(serviceIpUrl+imageFile);
//        }
//        if (videoFile.startsWith(sysBoard.getUrl())){
            sysFirst.setValue2(videoFile);
//        }else{
//            sysFirst.setValue2(serviceIpUrl+videoFile);
//        }
        return success(sysFirstService.updateSysFirst(sysFirst));
    }

    @PostMapping("/uploadHotelVideoFile")
    public AjaxResult uploadHotelVideoFile(MultipartFile file,HttpServletRequest request) throws Exception
    {
        String valueId = request.getParameter("valueId");
        String operName = getUsername();
        System.out.println(operName+"============"+valueId);
        System.out.println(file.getSize());
//        System.out.println(operName+"=============上传文件:"+files.size()+"============"+valueId);
//        String name = file.getName();
//        String uploadPathDir = PlayControlConfig.getUploadPath()+ File.separator+ DateUtils.dateTimeNow();
//        System.out.println("uploadPathDir:"+uploadPathDir);
//        File file1 = new File(uploadPathDir + File.separator + name);
//        file.transferTo(file1);
        // 上传文件路径
//        String filePath = PlayControlConfig.getUploadPath();
        String filePath = PlayControlConfig.getNginxRootPath()+ File.separator+ DateUtils.dateTimeNow();
        System.out.println("filePath:"+filePath);
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
//        SysBoard sysBoard = sysBoardService.selectSysBoardById(SysBoard.serviceFileId);
//        String serviceIpUrl = sysBoard.getUrl();
        System.out.println("fileName:"+fileName);
        SysFirst sysFirst = sysFirstService.selectSysFirstById(Long.valueOf(valueId));
//        sysFirst.setValue1(serviceIpUrl+fileName);
        sysFirst.setValue1(fileName);
        return success(sysFirstService.updateSysFirst(sysFirst));
    }
    @PostMapping("/uploadBackFile")
    public AjaxResult uploadBackFile(MultipartFile file,HttpServletRequest request) throws Exception
    {
        String valueId = request.getParameter("valueId");
        String operName = getUsername();
        System.out.println(operName+"=============上传文件:"+file.getSize()+"============"+valueId);
//        String name = file.getName();
//        String uploadPathDir = PlayControlConfig.getUploadPath()+ File.separator+ DateUtils.dateTimeNow();
//        System.out.println("uploadPathDir:"+uploadPathDir);
//        File file1 = new File(uploadPathDir + File.separator + name);
//        file.transferTo(file1);
        // 上传文件路径
//        String filePath = PlayControlConfig.getUploadPath();
        String filePath = PlayControlConfig.getNginxRootPath()+ File.separator+ DateUtils.dateTimeNow();
        System.out.println("filePath:"+filePath);
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
//        SysBoard sysBoard = sysBoardService.selectSysBoardById(SysBoard.serviceFileId);
//        String serviceIpUrl = sysBoard.getUrl();
        System.out.println("fileName:"+fileName);
        SysFirst sysFirst = sysFirstService.selectSysFirstById(Long.valueOf(valueId));
//        sysFirst.setValue1(serviceIpUrl+fileName);
        sysFirst.setValue1(fileName);
        sysFirst.setValue2("1"); //表示首页背景设置为图片
        return success(sysFirstService.updateSysFirst(sysFirst));
    }
    @GetMapping("/getRegions")
    public AjaxResult getRegions(HttpServletRequest request) {
        List<Region> regions = new ArrayList<>();
        String cityName = request.getParameter("city");
        if (StringUtils.isNotEmpty(cityName)){
            List<String> regionsByCity = CityRegionDataFromAPI.getRegionsByCity(cityName);
            Long index = 0l;
            for (String s : regionsByCity) {
                index++;
                Region region = new Region();
                region.setId(index);
                region.setName(s);
                regions.add(region);
            }
        }
        return success(regions);
    }


    /**
     * 获取终端首页配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:sysFirst:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        SysFirst sysFirst = sysFirstService.selectSysFirstById(id);
        if (id == 1){
            //配置地区,获取天气
            String city = sysFirst.getValue1();
            String region = sysFirst.getValue2();
            sysFirst.setCity(city);
            sysFirst.setRegion(region);
        }else if (id == SysFirst.top_left || id == SysFirst.top_right || id == SysFirst.lower_right || id == SysFirst.lower_left){
            sysFirst.setImageUrl(sysFirst.getValue1());
            sysFirst.setVideoUrl(sysFirst.getValue2());
        }
        return success(sysFirst);
    }


    @GetMapping(value = "/getWeather")
    public AjaxResult getWeather()
    {
        SysFirst sysFirst = sysFirstService.selectSysFirstById(SysFirst.weather);
        return success(sysFirst);
    }

    /**
     * 新增终端首页配置
     */
    @PreAuthorize("@ss.hasPermi('system:sysFirst:add')")
    @Log(title = "终端首页配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysFirst sysFirst)
    {
        return toAjax(sysFirstService.insertSysFirst(sysFirst));
    }

    /**
     * 修改终端首页配置
     */
    @PreAuthorize("@ss.hasPermi('system:sysFirst:edit')")
    @Log(title = "终端首页配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysFirst sysFirst)
    {
        Long id = sysFirst.getId();
        if (id == 1){
            //配置地区,获取天气
            String city = sysFirst.getCity();
            String region = sysFirst.getRegion();
            sysFirst.setValue1(city);
            if (StringUtils.isNotEmpty(region)){
                sysFirst.setValue2(region);
                city = region;
            }else{
                sysFirst.setValue2("");
            }
            System.out.println("获取天气城市:"+city);
            asynchWeatherService.updateCityWeather(sysFirst);
            return success(sysFirstService.updateSysFirst(sysFirst));
            //获取最新天气
        }else{
            return toAjax(sysFirstService.updateSysFirst(sysFirst));
        }

    }

    /**
     * 删除终端首页配置
     */
    @PreAuthorize("@ss.hasPermi('system:sysFirst:remove')")
    @Log(title = "终端首页配置", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysFirstService.deleteSysFirstByIds(ids));
    }
}
